<?php


namespace App\Models\CacheModel;


use App\Models\Api\BaseCache;
use think\Log;
use AstroTool\Cache\CacheManage;

class ZlBirthdayWish extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl_birthday_wish';
    protected $cacheModel = 'user.birthday_wish';

    /**
     * 获取祝福数据
     * @param int $id
     * @param array $field
     * @return array|bool|mixed|string
     * @throws \Exception
     */
    public function getWishInfo(int $id, array $field = [])
    {
        return CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->getDataAndSet(function () use ($id)
        {
            try
            {
                $data = $this->where('id', $id)->field('uid,self_rid,send_rid,wish,create_time,update_time')->findOrFail()->toArray();
            }
            catch (\Exception $e)
            {
                $data = [];
            }

            return $data;
        }, $field);
    }

    /**
     * 发送祝福
     * @param array $data
     * @return array|bool[]
     */
    public function sendWish(array $data)
    {
        if ($data['id'])
        { // 更新
            unset($data['send_rid'], $data['uid'], $data['self_rid']);
            $data['update_time'] = time();
            $this->isUpdate(true);
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $data['id'])->setCache($data);
        } else
        { // 新增
            unset($data['id']);
            $data['create_time'] = time();
        }

        try
        {
            $this->save($data);
        }
        catch (\Exception $e)
        {
            Log::write('生日许愿失败：' . $e->getMessage());
            return ['res' => false];
        }

        return ['res' => true, 'id' => $this->id];
    }
}
